﻿package com.ufenlei.LTS {
	import flash.display.Sprite;
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.net.URLRequest;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;

	public class ImageLoader extends Sprite {
		private var bitmap : Sprite = new Sprite();
		private var map : Bitmap = new Bitmap();
		private var mWidth : int;
		private var mHeight : int;
		private var ratio : Number;
		private var autoRatio : Boolean;
		private var imageLoader : Loader;
		private var mapURL : URLRequest;

		public function ImageLoader(mapWidth : int = 0,mapHeight : int = 0,ra : Boolean = false) {
			autoRatio = ra;
			mWidth = mapWidth;
			mHeight = mapHeight;
			imageLoader = new Loader();
		}

		public function load(url : String = null) : void {
			mapURL = new URLRequest(url);
			imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoadComplete);
			imageLoader.contentLoaderInfo.addEventListener(Event.OPEN, evtOpen);
			imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, reLoad);
			imageLoader.load(mapURL);
		}

		private function reLoad(evt : IOErrorEvent) : void {
			imageLoader.load(mapURL);
		}

		private function imageLoadComplete(event : Event) : void {
			addChild(bitmap);
			map = (event.target as LoaderInfo).content as Bitmap;
			bitmap.addChild(map);
			if (autoRatio == true) {
				ratio = bitmap.width / bitmap.height;
				if (mWidth >= mHeight * ratio) {
					this.width = mHeight * ratio;
					this.height = mHeight;
				} else {
					this.width = mHeight * ratio;
					this.height = mHeight;
				}
			} else {
				this.width = mWidth;
				this.height = mHeight;
			}
			this.addChild(bitmap);
			var completeEvent : Event = new Event("complete");
			this.dispatchEvent(completeEvent);
		}

		private function evtOpen(evt : Event) : void {
			this.dispatchEvent(new Event(Event.OPEN));
		}
	}
}